package com.erps.CommonUtils;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUrlTool {
	private static final Logger log = LoggerFactory.getLogger(HttpUrlTool.class);

	public Boolean HttpPostData(String cUrl, Map<String, String> params) {
		String retString = "";
		HttpClient client = new HttpClient();

		PostMethod vMethod = new PostMethod(cUrl);
		vMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
				"utf-8");

		int iLength = (params == null) ? 0 : params.size();
		NameValuePair[] vs = new NameValuePair[iLength];
		// 设置Http Post数据
		if (params != null) {
			int i = 0;
			for (Map.Entry<String, String> entry : params.entrySet()) {
				String cKeyName = entry.getKey();
				String cKeyValue = entry.getValue();
				NameValuePair vKey = new NameValuePair(cKeyName, cKeyValue);
				vs[i] = vKey;
				i++;
			}
		}
		vMethod.setRequestBody(vs);
		try {
			client.executeMethod(vMethod);
			if (vMethod.getStatusCode() == HttpStatus.SC_OK) {
				retString = vMethod.getResponseBodyAsString();
			}
		} catch (IOException e) {
			log.error("执行HTTP Post请求" + cUrl + "时，发生异常！", e);
		} finally {
			vMethod.releaseConnection();
		}
		return retString.trim().equals("1");
	}

	public String HttpGetData(String cUrl) {
		String retString = "";
		HttpClient client = new HttpClient();

		GetMethod vMethod = new GetMethod(cUrl);
		vMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
				"utf-8");
		try {
			client.executeMethod(vMethod);
			if (vMethod.getStatusCode() == HttpStatus.SC_OK) {
				retString = vMethod.getResponseBodyAsString();
			}
		} catch (IOException e) {
			log.error("执行HTTP Post请求" + cUrl + "时，发生异常！", e);
		} finally {
			vMethod.releaseConnection();
		}
		return retString;
	}

}
